package com.gpt.article.controller;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.document.utils.CsvWriter;
import com.document.utils.PoiUtils;
import com.gpt.article.domain.GptTopicContent;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.LawList;
import com.gpt.article.service.ILawListService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 全国律师列Controller
 * 
 * @author zhuzi
 * @date 2024-01-08
 */
@RestController
@RequestMapping("/article/lawlist")
public class LawListController extends BaseController
{
    @Autowired
    private ILawListService lawListService;

    /**
     * 查询全国律师列列表
     */
    @PreAuthorize("@ss.hasPermi('article:lawlist:list')")
    @GetMapping("/list")
    public TableDataInfo list(LawList lawList)
    {
        startPage();
        List<LawList> list = lawListService.selectLawListList(lawList);
        return getDataTable(list);
    }

    /**
     * 导出全国律师列列表
     */
//    @PreAuthorize("@ss.hasPermi('article:lawlist:export')")
//    @Log(title = "全国律师列", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, LawList lawList)
//    {
//        List<LawList> list = lawListService.selectLawListList(lawList);
//        ExcelUtil<LawList> util = new ExcelUtil<LawList>(LawList.class);
//        util.exportExcel(response, list, "全国律师列数据");
//    }

    /**
     * 导出大纲文章内容列表
     */
    @PreAuthorize("@ss.hasPermi('article:topicContent:export')")
    @Log(title = "大纲文章内容", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, GptTopicContent gptTopicContent) throws IOException {
        String jdbcURL = "jdbc:mysql://localhost:3306/chat-comparer?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true";
        String username = "root";
        String password = "123456";

        String csvFilePath = "D:/law_list_2.csv";
        try {
            // 加载MySQL JDBC驱动
            Class.forName( "com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found");
            e.printStackTrace();
            return;
        }
        try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {
//            for(int i=0;i<6;i++){
//                int pageSize  = 50000;
//                int curentPage = i*pageSize;
//                String limitStr = " limit "+curentPage+","+pageSize;
//
//            }
            String sql = " SELECT province,city,law_firm,licnumber,law_name  FROM  law_list limit 0,9999999";
//            String sql = "SELECT b.id, b.gen_content,b.gen_catalog,b.title,b.keyWords,b.customId FROM gpt_topic_title a  LEFT JOIN  gpt_topic_content b ON a.content_id = b.id WHERE a.id > '285988' AND a.content_id IS NOT NULL ORDER BY b.customId ASC";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setFetchSize(500); // 设置每次获取的数据量
            ResultSet result = statement.executeQuery();
            //表头
            String[] title = new String[]{"province", "city", "SummaryA", "PRT Words", "ID"};
            File tempFile = File.createTempFile("vehicle", ".csv");
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', StandardCharsets.UTF_8);
            csvWriter.writeRecord(title);
            while (result.next()) {
                String province = result.getString("province");
                String city = result.getString("city");
                String law_firm = result.getString("law_firm");
                String licnumber = "'"+result.getString("licnumber");
                String law_name = result.getString("law_name");
//                int id = result.getInt("customId");

                String[] data = new String[]{province, city, law_firm, licnumber, law_name};
                for (String datum : data) {
                    csvWriter.write(datum, true);
                }
                csvWriter.endRecord();

            }
            statement.close();
            csvWriter.close();
            //输出csv流文件，提供给浏览器下载
            PoiUtils.outCsvStream(response, tempFile);
            //删除临时文件
            PoiUtils.deleteFile(tempFile);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 获取全国律师列详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:lawlist:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(lawListService.selectLawListById(id));
    }

    /**
     * 新增全国律师列
     */
    @PreAuthorize("@ss.hasPermi('article:lawlist:add')")
    @Log(title = "全国律师列", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LawList lawList)
    {
        return toAjax(lawListService.insertLawList(lawList));
    }

    /**
     * 修改全国律师列
     */
    @PreAuthorize("@ss.hasPermi('article:lawlist:edit')")
    @Log(title = "全国律师列", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LawList lawList)
    {
        return toAjax(lawListService.updateLawList(lawList));
    }

    /**
     * 删除全国律师列
     */
    @PreAuthorize("@ss.hasPermi('article:lawlist:remove')")
    @Log(title = "全国律师列", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(lawListService.deleteLawListByIds(ids));
    }


    @GetMapping("/spider")
    public AjaxResult spider()
    {
        return toAjax(lawListService.spiderLaw());
    }

    @GetMapping("/spiderEn")
    public AjaxResult spiderEn()
    {
        return toAjax(lawListService.spiderENL());
    }










}
